// 全局变量
let currentPage = 1;
let pageSize = 10;
let totalData = [];
let total = 0;

// const paginationInfo = document.getElementById('paginationInfo');

// 生成分页按钮
function generatePaginationButtons(filteredData) {
    totalData = filteredData;
    total = filteredData.length;
    const totalPages = Math.ceil(total / pageSize);


    pagination.innerHTML = '';
    console.log(totalPages);

    // 如果只有一页，不显示分页按钮
    if (totalPages <= 1) {
        return;
    }

    // 添加首页按钮
    addPaginationButton('首页', 1, currentPage === 1);

    // 添加上一页按钮
    addPaginationButton('上一页', currentPage - 1, currentPage === 1);

    // 计算需要显示的页码范围
    const visiblePages = 5; // 最多显示5个页码
    let startPage = Math.max(1, currentPage - Math.floor(visiblePages / 2));
    let endPage = Math.min(totalPages, startPage + visiblePages - 1);

    // 调整起始页，确保显示足够的页码
    if (endPage - startPage + 1 < visiblePages) {
        startPage = Math.max(1, endPage - visiblePages + 1);
    }

    // 添加页码按钮
    for (let i = startPage; i <= endPage; i++) {
        addPaginationButton(i, i, false, i === currentPage);
    }

    // 添加下一页按钮
    addPaginationButton('下一页', currentPage + 1, currentPage === totalPages);

    // 添加末页按钮
    addPaginationButton('末页', totalPages, currentPage === totalPages);
}

// 添加分页按钮
function addPaginationButton(text, pageNum, isDisabled, isActive = false) {
    const li = document.createElement('li');
    const button = document.createElement('button');

    button.textContent = text;
    button.disabled = isDisabled;
    if (isActive) {
        button.classList.add('active');
    }

    // 绑定点击事件
    button.addEventListener('click', () => {
        goToPage(pageNum);
    });

    li.appendChild(button);
    pagination.appendChild(li);
}

// 跳转到指定页
function goToPage(pageNum) {
    const totalPages = Math.ceil(total / pageSize);

    // 验证页码有效性
    if (pageNum < 1 || pageNum > totalPages) {
        return;
    }

    currentPage = pageNum;
    renderCurrentPage();

    // 滚动到表格顶部
    // dataTable.scrollIntoView({ behavior: 'smooth' });
}

// 更新分页信息
function updatePaginationInfo() {
    const startItem = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
    const endItem = Math.min(currentPage * pageSize, total);
    // paginationInfo.textContent = `显示 ${startItem}-${endItem} 条，共 ${total} 条`;
}

// 处理每页显示条数变化
function handlePageSizeChange() {
    pageSize = parseInt(this.value);
    currentPage = 1; // 重置到第一页
    renderCurrentPage();
}

// 渲染当前页数据
function renderCurrentPage() {
    // 计算当前页数据的起始和结束索引
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + parseInt(pageSize);

    // 获取当前页数据
    const currentData = totalData.slice(startIndex, endIndex);
    console.log(currentData);

    // 渲染表格
    // renderTable(currentData);

    // 更新分页信息
    updatePaginationInfo();

    // 生成分页按钮
    generatePaginationButtons(currentData);

}